package com.example.ch02_student.adminsDo;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.ch02_student.AdminsMain;
import com.example.ch02_student.Login;
import com.example.ch02_student.R;
import com.example.ch02_student.TeacherMain;
import com.example.ch02_student.utils.ResultVo;
import com.example.ch02_student.utils.RoleInfo;
import com.example.ch02_student.utils.UrlBase;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import lombok.SneakyThrows;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AdminsDo extends AppCompatActivity {
    private Button teacherInfo, addTeacher;
    private EditText filePath, filePathCourse;
    private OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admins_do);

        filePath = findViewById(R.id.filePath);
        filePathCourse = findViewById(R.id.filePathCourse);
        okHttpClient = new OkHttpClient();
    }

    //回到管理员信息 界面
    public void index(View view) {
        if (RoleInfo.INT_ROLE == 1) {
            Intent intent = new Intent(AdminsDo.this, AdminsMain.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(AdminsDo.this, TeacherMain.class);
            startActivity(intent);
        }

    }

    //显示老师信息
    public void teacherInfo(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("sTeaInfo")) {
            Intent intent = new Intent(AdminsDo.this, TeacherInfo.class);
            startActivity(intent);
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();
        }

    }

    //添加老师信息
    public void addTeacher(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("aTeaInfo")) {
            Intent intent = new Intent(AdminsDo.this, AddTeacherInfo.class);
            startActivity(intent);
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();
        }

    }

    //显示学生成绩信息
    public void studentInfo(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("sGraInfo")) {
            Intent intent = new Intent(AdminsDo.this, StudentInfo.class);
            startActivity(intent);
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();

        }

    }

    //学生信息
    public void searchStudentInfo(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("sStuInfo"))
            startActivity(new Intent(AdminsDo.this, StudentSelfInfo.class));
    }

    //批量添加学生信息
    public void multiAddStu(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("aStuInfo")) {
            /*String s=filePath.getText()+"";
            Request build = new Request.Builder().url(UrlBase.URL_BASE+"/teacher/importStudentInfo?filePath="+s).build();
            Call call = okHttpClient.newCall(build);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()){
                        Looper.prepare();
                        Toast.makeText(AdminsDo.this,"导入成功",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }else {
                        Looper.prepare();
                        Toast.makeText(AdminsDo.this,"导入失败",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                }
            });*/
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            System.err.println("文件上传按钮");
            ActivityCompat.requestPermissions(AdminsDo.this,
                    new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 1);
            startActivityForResult(intent, 1);
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();
        }


    }

    //查看课程信息
    public void courseInfo(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("sCouInfo")) {
            startActivity(new Intent(AdminsDo.this, CourseInfo.class));
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();

        }

    }

    //批量导入课程信息
    public void multiAddCourse(View view) {
        if (RoleInfo.INT_ROLE == 1 || RoleInfo.PERSSIONS.contains("aCouInfo")) {
           /* String s=filePathCourse.getText()+"";
            Request build = new Request.Builder().url(UrlBase.URL_BASE+"/course/addMultiCourse?filePath="+s).build();
            Call call = okHttpClient.newCall(build);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String string = response.body().string();
                    ResultVo resultVo = new Gson().fromJson(string, ResultVo.class);
                    if (resultVo.getCode()==1000){
                        Looper.prepare();
                        Toast.makeText(AdminsDo.this,"导入成功",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }else {
                        Looper.prepare();
                        Toast.makeText(AdminsDo.this,"导入失败",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                }
            });*/
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            System.err.println("文件上传按钮");
            ActivityCompat.requestPermissions(AdminsDo.this,
                    new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 1);
            startActivityForResult(intent, 2);
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();
        }

    }


    //初始化控件
    public void init() {

    }

    //权限管理
    public void shiroMan(View view) {
        if (RoleInfo.INT_ROLE == 1) {
            startActivity(new Intent(AdminsDo.this, Shiro_manneage.class));
        } else {
            Toast.makeText(AdminsDo.this, "无此权限", Toast.LENGTH_SHORT).show();
        }
    }

    //退出登录
    public void exit(View view) {
        startActivity(new Intent(AdminsDo.this, Login.class));
    }

    //文件上传按钮
    public void fileup(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        System.err.println("文件上传按钮");
        ActivityCompat.requestPermissions(AdminsDo.this,
                new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 1);
        startActivityForResult(intent, 1);

    }

    //批量上传回调函数
    @SneakyThrows
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onActivityResult(final int requestCode, int resultCode, @Nullable Intent data) {


            Uri uri = data.getData();
            System.err.println("getpath" + uri.getPath());
            //本地 文件位置
            String path = uri.getPath().substring(uri.getPath().indexOf(":") + 1);
            File file1 = new File(path);
            //File file1 = new File("/storage/self/primary/Download/studentInfo.xlsx");
            System.err.println("path "+path);

        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "file", RequestBody.create(file1, MediaType.parse("multipart/form-data")))
                .addFormDataPart("filename", "file")
                .build();
        String a=null;
        if (requestCode==1){
            a=UrlBase.URL_BASE+"/teacher/importStudentInfo1";
        }else {
            a=UrlBase.URL_BASE+"/course/addMultiCourse";
        }
        Request request = new Request.Builder()
                .url(a)
                .post(body).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                Toast.makeText(AdminsDo.this, "error", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.code()==200){
                    Looper.prepare();
                    Toast.makeText(AdminsDo.this, "success", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }else {
                    Looper.prepare();
                    Toast.makeText(AdminsDo.this, "error", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });

/*

        FileInputStream in = new FileInputStream(file1);
            byte[] bytes = new byte[102400];
            int len = 0;
            String s = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((len = in.read(bytes)) != -1) {
                s = new String(bytes, 0, len);
                stringBuilder.append(s);
            }

            */
/* multipart/form-data*//*

            final String finalS = stringBuilder.toString();
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    URL url=null;
                    if (requestCode == 1) {
                        url = new URL(UrlBase.URL_BASE+"/teacher/importStudentInfo1");
                    }else {
                        url = new URL(UrlBase.URL_BASE+"/course/addMultiCourse");
                    }

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("POST");

                    //connection.setRequestProperty("Connection", "Keep-Alive");charset=utf-8
                    connection.setRequestProperty("Content-Type","multipart/form-data;boundary=12121");
                    //connection.setRequestProperty("Content-Length", String.valueOf(finalS.length()));

                    connection.setDoOutput(true);//application/vnd.ms-excel //application/json
                    connection.setDoInput(true);
                    connection.connect();

                    OutputStream opt = connection.getOutputStream();
                    opt.write(finalS.getBytes());

                    int code = connection.getResponseCode();
                    if (code == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(AdminsDo.this, "success", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(AdminsDo.this, "error", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }).start();
*/



    }
}
